import { defineComponent, h } from 'vue';
import type { PropType } from 'vue';
import  { createFromIconfontCN } from '@ant-design/icons-vue';
import * as AntIcon from '@ant-design/icons-vue';
import { useVisualConfigStore } from '@/visual/stores/visual-config';
import { DynamicIconEnum } from '@/visual/commons/enums/dynamic-icon-enum';
import CommonUtil from '@/visual/commons/utils/common-util';

export default defineComponent({
  name: 'DynamicIcon',
  props: {
    iconName: {
      type: String,
      default: '',
    },
    iconProps: {
      type: Object,
      default: () => {},
    },
    tagIconCls: {
      type: Array as PropType<string[]>,
      default: () => [],
    },
  },
  setup(props) {
    const useVisualConfig = useVisualConfigStore();
    const extendFontIconUrlsConfig = useVisualConfig.getExtendFontIconUrls;
    let HvIconFont: any;
    if (extendFontIconUrlsConfig) {
      HvIconFont = createFromIconfontCN({
        scriptUrl: (extendFontIconUrlsConfig as Array<any>) || [],
      });
    }

    const getIcon = () => {
      if (props.iconName?.indexOf(DynamicIconEnum.SvgIcon) !== -1) {
        return <hv-svg-icon name={props.iconName} {...props.iconProps} />;
      }

      if ( props.iconName?.indexOf(CommonUtil.replaceStrCase(DynamicIconEnum.SvgIcon)) !== -1) {
        const iconName = CommonUtil.svgIconToLowerCase(props.iconName);
        return <hv-svg-icon name={iconName} {...props.iconProps} />;
      }

      if (props.iconName?.indexOf(DynamicIconEnum.IconFont) !== -1) {
        const iconFont = props.iconName?.replace(DynamicIconEnum.IconFont, '');
        return <HvIconFont type={iconFont as string} {...props.iconProps} />;
      }

      if (props.iconName?.indexOf(DynamicIconEnum.TagIcon) !== -1) {
        const tagIcon = props.iconName?.replace(DynamicIconEnum.TagIcon, '');
        const classList = ['iconfont', tagIcon].concat(props.tagIconCls ? props.tagIconCls : []);
        return <span class={classList.join(' ')} {...props.iconProps} />;
      }

      let iconName = props.iconName;
      if (iconName.indexOf('-') != -1) {
        iconName = CommonUtil.replaceStrCase(props.iconName);
      }

      if (AntIcon[iconName] !== undefined) {
        return h(AntIcon[iconName], props.iconProps);
      }

      return <span />;
    };

    return () => <span>{getIcon()}</span>;
  },
});
